package com.example.lenovo.mywechat.homepage.mail_list;

import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lenovo.mywechat.MainActivity;
import com.example.lenovo.mywechat.R;
import com.example.lenovo.mywechat.homepage.Homepage;
import com.example.lenovo.mywechat.homepage.HomepageActivity;
import com.example.lenovo.mywechat.server_config.ServerConfig;
import com.snow.proto.my_wechat.FriendInfo;
import com.snow.proto.my_wechat.FriendInfoList;
import com.snow.proto.my_wechat.MyWeChatServiceGrpc;
import com.snow.proto.my_wechat.UserId;

import java.util.ArrayList;
import java.util.List;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class MailListFragment extends Fragment {


    public MailListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.mail_list_content, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);



        MyWeChatServiceGrpc.MyWeChatServiceBlockingStub blockingStub = MyWeChatServiceGrpc.newBlockingStub(HomepageActivity.managedChannel);

        FriendInfoList friendInfoList = blockingStub.getFriendInfoListByUserId(
                UserId.newBuilder().setUserId(HomepageActivity.userInfo.getId()).build()
        );

        FriendInfo friendInfo;
        int count = friendInfoList.getFriendInfoCount();
        Friend friend;
        List<Friend> friendList = new ArrayList<>();
        for (int i = 0; i < count; i++){
            friendInfo = friendInfoList.getFriendInfo(i);

            friend = new Friend(friendInfo.getGroupId(),
                    friendInfo.getId(),
                    friendInfo.getAvatarType(),
                    friendInfo.getAvatar(),
                    friendInfo.getName());
            friendList.add(friend);
        }

        FriendAdapter friendAdapter = new FriendAdapter(friendList, this.getActivity());

        RecyclerView recyclerView = getActivity().findViewById(R.id.mail_list_content_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(friendAdapter);
    }
}
